package com.ryan.security.interceptors;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by kaimin on 1/1/2019.
 * time : 10:52
 */
@Component //和过滤器不一样，加这个注解之后还要加WebConfig里面的东西
public class Timeinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        System.out.println("preHandle");
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod)handler).getMethod().getName());
        httpServletRequest.setAttribute("startTime",new Date().getTime());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        httpServletRequest.setAttribute("startTime",new Date().getTime());
        long startTime = (long)httpServletRequest.getAttribute("startTime");
        System.out.println("time 耗时："+(new Date().getTime()-startTime));

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");
        httpServletRequest.setAttribute("startTime",new Date().getTime());
        long startTime = (long)httpServletRequest.getAttribute("startTime");
        System.out.println("time 耗时："+(new Date().getTime()-startTime));
        System.out.println("ex is"+e);
    }
}
